const baseURL = "https://pcapi-xiaotuxian-front-devtest.itheima.net";
import { useMemberStore } from "@/store/member";

uni.addInterceptor("request", {
  invoke(args) {
    // args：拦截到的api的参数
    console.log(args);
    // 拼接基地址
    args.url = baseURL + args.url;
    // 统一添加请求头
    const memberStore = useMemberStore();
    const token = memberStore.profile.token;
    args.header = args.header || {};
    if (token) {
      args.header.Authorization = token;
    }
  },
});

uni.addInterceptor("uploadFile", {
  invoke(args) {
    // args：拦截到的api的参数
    console.log(args);
    // 拼接基地址
    args.url = baseURL + args.url;
    // 统一添加请求头
    const memberStore = useMemberStore();
    const token = memberStore.profile.token;
    args.header = args.header || {};
    if (token) {
      args.header.Authorization = token;
    }
  },
});

type Data<T> = {
  code: string;
  msg: string;
  result: T;
};

// 封装一个请求方法，让他支持promise风格
const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<T>((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        if (res.statusCode === 200) {
          // 剥离无效数据
          resolve((res.data as Data<T>).result);
        } else {
          reject(res);
        }
      },
    });
  });
};

export default http;
